package com.ihrm.modules.sys.shiro;

import com.ihrm.common.utils.RedisKeys;
import com.ihrm.common.utils.RedisUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

public class RedisSessionDAO extends EnterpriseCacheSessionDAO {

	@Autowired
	private RedisUtils redisUtils;

	/**
	 * 创建session，保存到redis集群中
	 */
	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = super.doCreate(session);
//		System.out.println("sessionId: " + sessionId);
		this.saveSession(session);
		return sessionId;
	}

	public void saveSession(Session session) {
		if (null != session || session.getId() != null) {
			redisUtils.set(RedisKeys.getShiroSessionKey(session.getId().toString()), session);
		}
	}

	/**
	 * 获取session
	 * @param sessionId
	 * @return
	 */
	@Override
	protected Session doReadSession(Serializable sessionId) {
		// Session session = super.doReadSession(sessionId);
		if (null != sessionId) {
			return redisUtils.get(RedisKeys.getShiroSessionKey(sessionId.toString()), Session.class);
		}

		return null;
	}

	/**
	 * 更新session
	 * @param session
	 */
	@Override
	protected void doUpdate(Session session) {
//		super.doUpdate(session);
		this.saveSession(session);

	}

	/**
	 * 删除失效session
	 */
	@Override
	protected void doDelete(Session session) {
		if (null != session) {
			redisUtils.delete(RedisKeys.getShiroSessionKey(session.getId().toString()));
		}

	}

}
